<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
<!--      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>-->
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="ID号" prop="idCode">
        <el-input
          v-model="queryParams.idCode"
          placeholder="请输入ID号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="治疗方案" prop="preferredPlan">
        <el-select
          v-model="queryParams.preferredPlan"
          placeholder="请选择首选治疗方案"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_PRE_PLAN)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待分配" :value="0" />
          <el-option label="已分配" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="医生" prop="doctorId">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入分配的医生姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="风险等级" prop="riskLevel">
        <el-select
          v-model="queryParams.riskLevel"
          placeholder="请选择风险等级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_RISK_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-width="85" label="就诊人标签" prop="locationIds">
        <el-cascader
          v-model="queryParams.tags"
          :options="tagsTree"
          :props="{ multiple: true }"
          clearable
          style="width: 100%"
        />
      </el-form-item>
<!--      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['business:user-patient:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['business:user-patient:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['business:user-patient:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="ID" align="center" prop="id" />
<!--      <el-table-column label="用户ID" align="center" prop="userId" />-->
      <el-table-column label="基本信息" align="left" prop="name">
        <template #default="{row}">
          <p>姓名：{{row.name}}</p>
          <p>手机号：{{row.mobile}}</p>
          <p>身份证号：{{row.idCard}}</p>
          <p>出生日期：{{row.birthday}}</p>
          <p>ID号：{{row.idCode}}</p>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="{row}">
          <el-tag v-if="row.status">已分配</el-tag>
          <el-tag type="warning" v-else>待分配</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分配的医生" align="center" prop="doctorName" />
      <el-table-column label="风险等级" align="center" prop="riskLevel">
        <template #default="{row}">
<!--          <dict-tag :type="DICT_TYPE.BUSINESS_USER_PATIENT_RISK_LEVEL" :value="scope.row.riskLevel" />-->
          <el-image
            v-if="row.riskLevel == 3"
            class="h-50px w-50px"
            lazy
            src="https://suifang2025.hncykj.xyz/images/danger.png"
            :preview-src-list="['https://suifang2025.hncykj.xyz/images/danger.png']"
            preview-teleported
            fit="contain"
          />
          <el-image
            v-else-if="row.riskLevel == 2"
            class="h-50px w-50px"
            lazy
            src="https://suifang2025.hncykj.xyz/images/warning.png"
            :preview-src-list="['https://suifang2025.hncykj.xyz/images/warning.png']"
            preview-teleported
            fit="contain"
          />
          <el-image
            v-else-if="row.riskLevel == 1"
            class="h-50px w-50px"
            lazy
            src="https://suifang2025.hncykj.xyz/images/primary.png"
            :preview-src-list="['https://suifang2025.hncykj.xyz/images/primary.png']"
            preview-teleported
            fit="contain"
          />
          <el-image
            v-else
            class="h-50px w-50px"
            lazy
            src="https://suifang2025.hncykj.xyz/images/success.png"
            :preview-src-list="['https://suifang2025.hncykj.xyz/images/success.png']"
            preview-teleported
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column label="地址信息" align="left" prop="location" min-width="120px">
        <template #default="{row}">
          <p>
            居住地：<span v-for="(l, i) in row.location" :key="i">{{l}}</span>
          </p>
          <p>详细地址：{{ row.locationDetail }}</p>
        </template>
      </el-table-column>
      <el-table-column label="确诊年龄" align="center" prop="confirmedDiagnosisAge" />
      <el-table-column label="特病症" align="center" prop="specialIllness">
        <template #default="{row}">
          <el-tag type="danger" v-if="row.specialIllness">是</el-tag>
          <el-tag type="info" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="180px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="doctorAllotShow(scope.row.id, scope.row.doctorId)"
            v-hasPermi="['business:user-patient:doctor.allot']"
          >
            分配医生
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['business:user-patient:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="medicalVisitRecord(scope.row.id, scope.row.name)"
            v-hasPermi="['business:user-patient:update']"
          >
            就诊记录
          </el-button>
<!--          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:user-patient:delete']"
          >
            删除
          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>


  <Dialog v-model="doctorAllotDialogVisible" title="就诊人医生分配" width="600">
    <el-form label-width="70px">
      <el-form-item label="就诊医生" prop="doctorId">
        <el-select
          v-model="doctorId"
          placeholder="请选择就诊医生"
          clearable
          class="!w-450px"
        >
          <el-option
            v-for="doctor in doctors"
            :key="doctor.id"
            :label="doctor.nickname"
            :value="doctor.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="doctorAllotSubmitForm">确 定</el-button>
      <el-button @click="doctorAllotDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 表单弹窗：添加/修改 -->
  <UserPatientForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import {getStrDictOptions, DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { UserPatientApi, UserPatient } from '@/api/business/userpatient'
import UserPatientForm from './UserPatientForm.vue'
import {TagApi} from "@/api/business/tag";
import {ContentWrap} from "@/components/ContentWrap";

const route = useRoute() // 路由
const router = useRouter() // 路由

/** 就诊人 列表 */
defineOptions({ name: 'UserPatient' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<UserPatient[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  name: undefined,
  mobile: undefined,
  idCard: undefined,
  birthday: undefined,
  idCode: undefined,
  preferredPlan: undefined,
  status: undefined,
  doctorName: undefined,
  riskLevel: undefined,
  tags: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const tagsTree = ref() // 树形结构

/** 获得已开通城市树 */
const getTagsTree = async () => {
  tagsTree.value = await TagApi.getTagTree()
}

let doctors = ref([])
let doctorAllotDialogVisible = ref(false)
let recordId = ref()
let doctorId = ref()

/** 分配医生显示表单 */
const doctorAllotShow = async (id:number, doctorIdParam:number) => {
  recordId.value = undefined
  doctorId.value = undefined
  recordId.value = id
  doctorId.value = doctorIdParam
  doctorAllotDialogVisible.value = true
  doctors.value = await UserPatientApi.getAllDoctors();
}

/** 分配医生提交 */
const doctorAllotSubmitForm = async () => {
  const data = {id: recordId.value, doctorId: doctorId.value};
  await UserPatientApi.userPatientDoctorAllot(data)
  message.success(t('common.createSuccess'))
  doctorAllotDialogVisible.value = false
  await getList()
}

/** 就诊记录页面跳转 */
const medicalVisitRecord = async (id:number, name:string) => {
  router.push({
    name: 'MedicalVisitRecord',
    query: { id, name }
  })
}


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserPatientApi.getUserPatientPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserPatientApi.deleteUserPatient(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除就诊人 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await UserPatientApi.deleteUserPatientList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: UserPatient[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserPatientApi.exportUserPatient(queryParams)
    download.excel(data, '就诊人.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getTagsTree()
})
</script>
